﻿using System;
using FluentValidation;
using FluentValidation.Results;
using GiveAQuiz.Web.Helpers;
using GiveAQuiz.Web.Membership;
using GiveAQuiz.Web.Models;

namespace GiveAQuiz.Web.Validation
{
  /// <summary>
  /// Validate the ChangePasswordViewModel
  /// </summary>
  public class ChangePasswordValidator : AbstractValidator<ChangePasswordViewModel>
  {
    /// <summary>
    /// Creates a new instance of the ChangePasswordValidator
    /// </summary>
    /// <param name="membershipSvc">The IMembershipService interface.</param>
    public ChangePasswordValidator(IMembershipService membershipSvc)
    {
      // old password
      RuleFor(cp => cp.CurrentPassword).NotBlank().WithMessage("The current password is required");

      // new password
      RuleFor(cp => cp.NewPassword).NotBlank().WithMessage("The new password is required");
      RuleFor(cp => cp.NewPassword.Length)
        .GreaterThanOrEqualTo(membershipSvc.MinPasswordLength)
        .When(cp => !String.IsNullOrWhiteSpace(cp.NewPassword))
        .WithMessage("The new password must have {0} or more characters", membershipSvc.MinPasswordLength);

      // confirm password
      RuleFor(cp => cp.RepeatPassword).NotBlank().WithMessage("The password confirmation is required");
      RuleFor(cp => cp.RepeatPassword.Length)
        .GreaterThanOrEqualTo(membershipSvc.MinPasswordLength)
        .When(cp => !String.IsNullOrWhiteSpace(cp.RepeatPassword))
        .WithMessage("The password confirmation must have {0} or more characters", membershipSvc.MinPasswordLength);
      
      // password and confirmation must match
      Custom(cp =>
        !String.IsNullOrWhiteSpace(cp.NewPassword) &&
        !String.IsNullOrWhiteSpace(cp.RepeatPassword) &&
        !cp.NewPassword.Equals(cp.RepeatPassword) ?
          new ValidationFailure("RepeatPassword", "The new password and confirmation do not match") : null);
    }
  }
}